package com.mygdx.snakegame;

import java.util.Vector;

public class Snake {
    Vector<Body> bodies;

    public Snake()
    {
        bodies=new Vector<>();
        bodies.add(new Body(26,17,Dir.Up));
        bodies.add(new Body(26,16,Dir.Up));
        bodies.add(new Body(26,15,Dir.Up));
    }

    void changeDir(Dir dir)
    {
        Dir rdir=Dir.Up;
        switch (bodies.get(0).dir)
        {
            case Up:
                rdir=Dir.Down;
                break;
            case Down:
                rdir=Dir.Up;
                break;
            case Left:
                rdir=Dir.Right;
                break;
            case Right:
                rdir=Dir.Left;
                break;
        }
        if(dir!=rdir)
        {
            bodies.get(0).dir=dir;
        }
    }

    public void move()
    {
        for(int i=0;i<bodies.size();i++)
        {
            switch (bodies.get(i).dir)
            {
                case Up:
                    ++(bodies.get(i).y);
                    break;
                case Down:
                    --(bodies.get(i).y);
                    break;
                case Left:
                    --(bodies.get(i).x);
                    break;
                case Right:
                    ++(bodies.get(i).x);
            }
        }
        for (int i = bodies.size()-1; i > 0; i--)
        {
            if (bodies.get(i).dir != bodies.get(i-1).dir)
                bodies.get(i).dir = bodies.get(i-1).dir;
        }
    }

    void add()
    {
        switch (bodies.lastElement().dir)
        {
                case Up:
                    bodies.add(new Body(bodies.lastElement().x, bodies.lastElement().y-1, Dir.Up));
                    break;
                case Down:
                    bodies.add(new Body(bodies.lastElement().x, bodies.lastElement().y+1, Dir.Down));
                    break;
                case Left:
                    bodies.add(new Body(bodies.lastElement().x+1, bodies.lastElement().y, Dir.Left));
                    break;
                case Right:
                    bodies.add(new Body(bodies.lastElement().x-1, bodies.lastElement().y, Dir.Right));
                    break;
        }
    }

    boolean death()
    {
        if(bodies.get(0).x==0||bodies.get(0).x==51||bodies.get(0).y==0||bodies.get(0).y==35)
        {
            return true;
        }
        for(int i=3;i<bodies.size();i++)
        {
            if(bodies.get(0).x==bodies.get(i).x&&bodies.get(0).y==bodies.get(i).y)
                return true;
        }
        return false;
    }

}
